from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from gather.weather import ParseWeather
from datetime import datetime
import math

app = Flask(__name__)
api = Api(app)

weather = ParseWeather()


# @api.resource('/')
# class HelloWorld(Resource):

#     def get(self):

#         return weather.batchResult(page, page_size)

# @api.resource('/html')
# class HtmlParse(Resource):

#     def get(self):
#         weather.parseHtml()


@api.resource('/weather')
class WeatherInfo(Resource):

    parse = reqparse.RequestParser()

    def __init__(self):
        self.parse.add_argument('page', type=int, default=1)
        self.parse.add_argument('page_size', type=int, choices=([5, 10]), default=5)

    def get(self):
        '''分页数据返回'''
        parse_parmas = self.parse.parse_args()
        page = parse_parmas.page
        page_size = parse_parmas.page_size
        counts, result = weather.batchResult(page, page_size)
        _pre, _next = None, None

        if page > 1:
            _pre = '%s?page=%s&page_size=%s' % (request.base_url, page - 1, page_size)
        if (page+1) <= math.ceil(float(counts)/float(page_size)):
            _next = '%s?page=%s&page_size=%s' % (request.base_url, page + 1, page_size)

        return {
            "counts":counts,
            "previous":_pre,
            "next":_next,
            "results":result,
        }